/****************************************************
          File Name:list_quque.h
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Tue 10 Feb 2015 09:38:04 AM CST
*****************************************************/

#ifndef list_quque_h_
#define list_quque_h_

#include <stdbool.h>
#include <stdio.h>

typedef int Mydata;

typedef struct node
{
    Mydata data;
    struct node *next;
} Node;
typedef struct QUEUE
{
    Node *front;
    Node *rear;
    int len;
} Queue;

int MAX;

void InitQueue(Queue **q, int len)
{
    *q = (Queue *)malloc(sizeof(Queue));
    (*q)->front = NULL;
    (*q)->rear = NULL;
    (*q)->len = 0;
    MAX = len;
}

void Destroy(Queue *q)
{
    Node *tmp;

    while(q->front != NULL)
    {
        tmp = q->front;
        q->front = q->front->next;
        printf("free: %d\n", tmp->data);
        free(tmp);
    }
}

bool isEmpty(Queue *q)
{
    return q->len == 0 ? true : false;
}

bool isFull(Queue *q)
{
    return q->len == MAX ? true : false;
}

bool EnQueue(Queue **q, Mydata e)
{
    Node *tmp;

    if(isFull(*q)) return false;

    tmp = (Node *)malloc(sizeof(Node));
    if(!tmp) return false;

    tmp->data = e;
    tmp->next = NULL;

    if((*q)->front == NULL)
        (*q)->front = tmp;
    else
        (*q)->rear->next = tmp;

    (*q)->rear = tmp;
    (*q)->len++;
    return true;
}

bool DeQueue(Queue **q, Mydata *e)
{
    Node *tmp;

    if(isEmpty(*q)) return false;

    tmp = (*q)->front;
    (*q)->front = (*q)->front->next;
    (*q)->len--;
    *e = tmp->data;

    free(tmp);
    return true;
}

int QueueLength(Queue *q)
{
    return q->len;
}

#endif
